package com.payment.controller.payment;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.payment.entity.pay.wxapp.request.RequestWeiXinAppPay;
import com.payment.entity.pay.wxapp.request.RequestWeiXinAppPayData;
import com.payment.entity.pay.wxapp.request.RequestWeiXinAppPayTradeData;
import com.payment.entity.pay.wxapp.response.ResponseWeiXinAppPay;
import com.payment.entity.pay.wxapp.response.ResponseWeiXinAppPayData;
import com.payment.entity.pay.wxapp.response.ResponseWeiXinAppPayTradeData;
import com.payment.service.SequenceService;
import com.payment.utils.MD5;
import com.payment.utils.UtilsInterfacesPackage;
import com.payment.utils.WxPayUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@Api(description = "微信APP内支付")
/**
 * 1，使用领科的微信收款账号收款，微信APP内支付接口：
 *
 * 2，适用于老的客户：适用于客户是app相对接微信支付的；
 *
 * 3，更新的数据表为：user_order_payment_manager_t；
 *
 *  4，更新的数据库为：links
 *
 * @author lm
 * @date 2019/11/06
 */
public class WeiXinPayAppController {

    private static Logger logger = Logger.getLogger(WeiXinPayAppController.class);
    @Autowired
    private SequenceService sequenceService;

    /***微信app支付付款接口
     *
     * @param requestWeiXinAppPay
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/wxAppPay", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @CrossOrigin
    @ResponseBody
    @ApiOperation(value = "微信支付下单", response = ResponseWeiXinAppPay.class)
    public String wxPayH5(@ApiParam @RequestBody RequestWeiXinAppPay requestWeiXinAppPay, HttpServletRequest request) throws Exception {
        // 1，生成流水号
        String connSeqNo = sequenceService.getPackageTaskNo();
        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curtime = df.format(new Date());
        //3，定义回报报文
        String jsonString;
        UtilsInterfacesPackage utils = new UtilsInterfacesPackage();
        String requestStr = JSON.toJSONString(requestWeiXinAppPay);
        if (requestStr == null) {
            logger.info("请求报文不合法:requestStr为空");
            jsonString = utils.dataWeiKong(connSeqNo, curtime);
            return jsonString;
        } else {
            logger.info("前端请求报文是：" + requestStr);
            RequestWeiXinAppPay requestPackage = JSONArray.parseObject(requestStr, RequestWeiXinAppPay.class);
            String requestSign = requestPackage.getSign();
            if (requestSign == null) {
                logger.info("请求报文不合法:sign为空");
                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                return jsonString;
            } else {
                logger.info("请求的签名是：" + requestSign);
                RequestWeiXinAppPayData requestData = requestPackage.getData();
                if (requestData == null) {
                    logger.info("请求报文不合法:data为空");
                    jsonString = utils.dataWeiKong(connSeqNo, curtime);
                    return jsonString;
                } else {
                    String partnerCode = requestData.getPartnerCode();
                    String ConnSeqNo = requestData.getConnSeqNo();
                    String tradeTime = requestData.getTradeTime();
                    String token = requestData.getToken();
                    String tradeType = requestData.getTradeType();
                    String lang = requestData.getLang();
                    RequestWeiXinAppPayTradeData requestTradeData = requestData.getTradeData();
                    if (requestTradeData == null || partnerCode == null || ConnSeqNo == null || tradeTime == null || token == null || tradeType == null || lang == null) {
                        logger.info("请求报文不合法:data参数不合法");
                        jsonString = utils.dataWeiKong(connSeqNo, curtime);
                        return jsonString;
                    } else {
                        String orderId = requestTradeData.getOrderId();
                        String amount = requestTradeData.getAmount();
                        String body = requestTradeData.getBody();
                        String APPID = requestTradeData.getAppId();
                        if (orderId == null || orderId == "" || amount == null || amount == "" || APPID == null || APPID == "" || body == null || body == "") {
                            logger.info("请求报文不合法:orderId,amount,APPID或者body不可以为空！");
                            jsonString = utils.dataWeiKong(connSeqNo, curtime);
                            return jsonString;
                        } else {
                            // 将请求体json转成String
                            String str = JSON.toJSONString(requestData);
                            // 将Str拿去计算签名
                            String sign = utils.calculateSignature(str);
                            logger.info("计算的签名是：" + sign);
                            if (!requestSign.equalsIgnoreCase(sign)) {
                                logger.info("签名验证失败！");
                                jsonString = utils.publicMessage(ConnSeqNo, partnerCode, tradeTime, token, tradeType);
                                return jsonString;
                            } else {
                                // 统一下单，返回xml，用return_code判断统一下单结果,获取prepay_id等预支付成功信息
                                // 获取ip地址:
                                String ipAddrStr = WxPayUtil.getIp2(request);
                                logger.info("新的获取的ip地址是：" + ipAddrStr);
                                // 将传过来的金额处理一下
                                boolean flag = WxPayUtil.isInteger(amount);
                                //商品描述
                                //String body = "领科-流量重值";
                                //String body = "IotCardTrafficRecharge";
                                //场景信息
                                //String scene_info = "{\"h5_info\":\"h5_info\" {\"type\":\"WAP\",\"wap_url\":\"http://wx.linksfield.net\",\"wap_name\":\"IotCardTrafficRecharge\"}}";
                                //APPID="wxd678efh567hg6787";
                                // 如果是整型
                                if (flag == true) {
                                    int Amount = Integer.valueOf(amount).intValue();
                                    int totel_fee = Amount * 100;
                                    String prePayInfoXml = WxPayUtil.UnifiedOrderAPP(body, orderId, totel_fee, ipAddrStr, APPID);
                                    logger.info("Controller中的prePayInfoXml：" + prePayInfoXml);
                                    // 生成包含prepay_id的map，map传入前端
                                    Map<String, Object> map = new HashMap<String, Object>();
                                    map = WxPayUtil.getPayAPPMap(prePayInfoXml);
                                    logger.info("Controller中的map：" + map);

                                    String prepay_id = (String) map.get("prepay_id");
                                    String trade_type = (String) map.get("trade_type");
                                    String return_msg = (String) map.get("return_msg");
                                    String return_code = (String) map.get("return_code");
                                    if (StringUtils.isNotBlank(prepay_id) && StringUtils.isNotBlank(trade_type) && return_code.equalsIgnoreCase("success")) {
                                        //回报报文TradeData
                                        ResponseWeiXinAppPayTradeData responseTradeData = new ResponseWeiXinAppPayTradeData();
                                        responseTradeData.setPrepay_id(prepay_id);
                                        responseTradeData.setTrade_type(trade_type);
                                        responseTradeData.setOrderId(orderId);
                                        //回报Data
                                        ResponseWeiXinAppPayData data = new ResponseWeiXinAppPayData();
                                        data.setConnSeqNo(ConnSeqNo);
                                        data.setPartnerCode(partnerCode);
                                        data.setToken(token);
                                        data.setTradeType(tradeType);
                                        data.setTradeTime(tradeTime);
                                        data.setTradeRstCode(1000);
                                        data.setTradeRstMessage("success");
                                        data.setTradeData(responseTradeData);

                                        ResponseWeiXinAppPay responseWeiXinPay = new ResponseWeiXinAppPay();
                                        responseWeiXinPay.setData(data);
                                        responseWeiXinPay.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                        // 返回给调用者的报文
                                        jsonString = JSON.toJSONString(responseWeiXinPay);
                                        logger.info("响应报文：" + jsonString);
                                        return jsonString;
                                    } else {
                                        //如果没有取到微信的预下单号，就返回错误
                                        //回报Data
                                        ResponseWeiXinAppPayData data = new ResponseWeiXinAppPayData();
                                        data.setConnSeqNo(ConnSeqNo);
                                        data.setPartnerCode(partnerCode);
                                        data.setToken(token);
                                        data.setTradeType(tradeType);
                                        data.setTradeTime(tradeTime);
                                        data.setTradeRstCode(1200);
                                        data.setTradeRstMessage(return_msg);

                                        ResponseWeiXinAppPay responseWeiXinPay = new ResponseWeiXinAppPay();
                                        responseWeiXinPay.setData(data);
                                        responseWeiXinPay.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                        // 返回给调用者的报文
                                        jsonString = JSON.toJSONString(responseWeiXinPay);
                                        logger.info("响应：" + jsonString);
                                        return jsonString;
                                    }
                                } else {
                                    // DecimalFormat("#")表示float类型格式化时不要小数点了
                                    DecimalFormat decimalFormat = new DecimalFormat("#");
                                    float Amount = Float.parseFloat(amount);
                                    int totel_fee = Integer.parseInt(decimalFormat.format(Amount * 100));
                                    String prePayInfoXml = WxPayUtil.UnifiedOrderAPP(body, orderId, totel_fee, ipAddrStr, APPID);
                                    logger.info("Controller中的prePayInfoXml：" + prePayInfoXml);
                                    // 生成包含prepay_id的map，map传入前端
                                    Map<String, Object> map = new HashMap<String, Object>();
                                    map = WxPayUtil.getPayAPPMap(prePayInfoXml);
                                    logger.info("Controller中的map：" + map);
                                    // 将订单号放入map，用以支付后处理
                                    String prepay_id = (String) map.get("prepay_id");
                                    String trade_type = (String) map.get("trade_type");
                                    String return_msg = (String) map.get("return_msg");
                                    String return_code = (String) map.get("return_code");

                                    if (StringUtils.isNotBlank(prepay_id) && StringUtils.isNotBlank(trade_type) && return_code.equalsIgnoreCase("success")) {
                                        //回报报文TradeData
                                        ResponseWeiXinAppPayTradeData responseTradeData = new ResponseWeiXinAppPayTradeData();
                                        responseTradeData.setPrepay_id(prepay_id);
                                        responseTradeData.setTrade_type(trade_type);
                                        responseTradeData.setOrderId(orderId);
                                        //回报Data
                                        ResponseWeiXinAppPayData data = new ResponseWeiXinAppPayData();
                                        data.setConnSeqNo(ConnSeqNo);
                                        data.setPartnerCode(partnerCode);
                                        data.setToken(token);
                                        data.setTradeType(tradeType);
                                        data.setTradeTime(tradeTime);
                                        data.setTradeRstCode(1000);
                                        data.setTradeRstMessage("success");
                                        data.setTradeData(responseTradeData);

                                        ResponseWeiXinAppPay responseWeiXinPay = new ResponseWeiXinAppPay();
                                        responseWeiXinPay.setData(data);
                                        responseWeiXinPay.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                        // 返回给调用者的报文
                                        jsonString = JSON.toJSONString(responseWeiXinPay);
                                        logger.info("响应：" + jsonString);
                                        return jsonString;
                                    } else {
                                        //如果没有取到微信的预下单号，就返回错误
                                        //回报Data
                                        ResponseWeiXinAppPayData data = new ResponseWeiXinAppPayData();
                                        data.setConnSeqNo(ConnSeqNo);
                                        data.setPartnerCode(partnerCode);
                                        data.setToken(token);
                                        data.setTradeType(tradeType);
                                        data.setTradeTime(tradeTime);
                                        data.setTradeRstCode(1200);
                                        data.setTradeRstMessage(return_msg);

                                        ResponseWeiXinAppPay responseWeiXinPay = new ResponseWeiXinAppPay();
                                        responseWeiXinPay.setData(data);
                                        responseWeiXinPay.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                        // 返回给调用者的报文
                                        jsonString = JSON.toJSONString(responseWeiXinPay);
                                        logger.info("响应报文：" + jsonString);
                                        return jsonString;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

}

